package com.code.soulnetty.modbus;

import io.netty.channel.EventLoopGroup;
import io.netty.channel.epoll.Epoll;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class EventLoopGroupProvider {

    Map<String, EventLoopGroup> groupMap = new HashMap<>(4);

    /**
     * 根据key获取对应的EventLoopGroup
     *
     * @param key 唯一key
     * @return
     */
    public EventLoopGroup get(String key) {
        EventLoopGroup eventExecutors = groupMap.get(key);
        if (eventExecutors != null) {
            return eventExecutors;
        }
        synchronized (groupMap) {
            eventExecutors = groupMap.get(key);
            if (eventExecutors != null) {
                return eventExecutors;
            }
            boolean available = Epoll.isAvailable();
            if (available) {
                eventExecutors = new EpollEventLoopGroup();
            } else {
                eventExecutors = new NioEventLoopGroup();
            }
            groupMap.put(key, eventExecutors);
            return eventExecutors;
        }
    }
}
